// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV,
});
const db = cloud.database({
  throwOnNotFound: false
});
const suffererOrbit = db.collection("suffererOrbit");
const suffererCity = db.collection("suffererCity");
const myOrbit = db.collection("myOrbit");
const _ = db.command;
const $ = _.aggregate;

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()

  console.log(" orbit  spider begin")
  var request = require("request");
  let res = await new Promise(function (resolve, reject) {
    request("http://whjy.mukton.com/data", function (error, res, body) {
      if (!error && res.statusCode == 200) {
        resolve(body);
      } else {
        reject(error);
      }
    });
  });
    var body = JSON.parse(res)["body"];
  var data = body["data"];
  var del = body["delete"];
  for (var i in data){
    await suffererOrbit.doc(data[i]["id"]).set({
      data:{
        province: data[i]["province"],
        city: data[i]["city"],
        date: data[i]["date"],
        des: data[i]["des"],
        name: data[i]["name"],
        who: data[i]["who"],
        url: data[i]["url"],
        location: {
          type: 'Point',
          coordinates: [data[i]['longitude'], data[i]['latitude']]
        }
      }
    });
    await myOrbit.where({
      city: data[i]["city"],
      date: data[i]["date"],
      location: _.geoNear({
        geometry: db.Geo.Point(data[i]['longitude'], data[i]['latitude']),
        maxDistance: 1000,
        })
      }).update({
        data:{
          dangerous:true,
          send:true,
        }
    });
  }
  
  for (var delIndex in del) {
    await suffererOrbit.doc(del[delIndex]).remove();
  } 

  var provinces = await suffererOrbit.aggregate()
    .group({
      _id:'$province',
      cities: $.addToSet('$city')
    }).end();

  var provincesList = provinces.list;
  for (var i in provincesList){
    console.log(provincesList[i]);
    let res = await suffererCity.doc(provincesList[i]._id).get();
    if (res.data == null){
      await suffererCity.add({
        data:{
          _id: provincesList[i]._id,
          citys: provincesList[i].cities
        }
      });
    }else{
      //注意文档错了，应该是$each
      await suffererCity.doc(provincesList[i]._id).update({
          data:{
            citys:_.addToSet({
              $each: provincesList[i].cities
            })
          }
        })
    }
  }

  return {
    success: true
  }
}